package com.eudon.design_pattern.behavioral.interpreter;

/**
 * @author eudon
 * @description 比较表达式，处理 > < >= <= == 等比较操作
 * @date 2025/9/3
 * @email syd19970616@gmail.com
 * @address <a href="https://gitee.com/eudon">Gitee</a>
 */
public class CompareExpression implements RuleExpression {
    private String apiName;      // 接口名称
    private String metricType;   // 指标类型："调用次数"、"失败次数"、"失败率"
    private String operator;     // 操作符：">"、"<"、">="、"<="、"=="
    private double threshold;    // 阈值

    public CompareExpression(String apiName, String metricType, String operator, double threshold) {
        this.apiName = apiName;
        this.metricType = metricType;
        this.operator = operator;
        this.threshold = threshold;
    }

    @Override
    public boolean interpret(Context context) {
        double actualValue = getActualValue(context);
        
        switch (operator) {
            case ">":
                return actualValue > threshold;
            case "<":
                return actualValue < threshold;
            case ">=":
                return actualValue >= threshold;
            case "<=":
                return actualValue <= threshold;
            case "==":
                return actualValue == threshold;
            default:
                return false;
        }
    }

    /**
     * 根据指标类型获取实际值
     */
    private double getActualValue(Context context) {
        switch (metricType) {
            case "调用次数":
                return context.getCallCount(apiName);
            case "失败次数":
                return context.getFailCount(apiName);
            case "失败率":
                return context.getFailRate(apiName);
            default:
                return 0;
        }
    }

    @Override
    public String toString() {
        return apiName + metricType + " " + operator + " " + threshold;
    }
}